package com.vanrui.pcp.autocode.defines;

import freemarker.core.Environment;
import freemarker.template.*;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

public class ParseType implements TemplateDirectiveModel{

	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
			throws TemplateException, IOException {
		// Check if no parameters were given:
//		if (!params.isEmpty()) {
//			throw new TemplateModelException("This directive doesn't allow parameters.");
//		}
		if (loopVars.length != 0) {
			throw new TemplateModelException("This directive doesn't allow loop variables.");
		}

		String type = String.valueOf(params.get("type"));
		if (body != null) {
			body.render(new ParseTypeWriter(env.getOut(), type));
		} else {
			throw new RuntimeException("missing body");
		}
	}
	
	private static class ParseTypeWriter extends Writer{

		
		private final Writer out;
		private final String type;
		
		public ParseTypeWriter(Writer out, String type){
			this.out = out;
			this.type = type;
		}
		
		@Override
		public void close() throws IOException {
			out.close();
		}

		@Override
		public void flush() throws IOException {
			out.flush();
			
		}

		@Override
		public void write(char[] cbuf, int off, int len) throws IOException {
			String str = String.valueOf(cbuf).trim();
			StringBuffer res = new StringBuffer();
			res.append(getParse(type));
			if(res.length() > 0){
				res.append("(_").append(str).append(")");
			}else{
				res.append("_").append(str);
			}
			out.write(String.valueOf(res).trim());/// 
		}
		
		private String getParse(String type){
			if("Integer".equalsIgnoreCase(type)){
				return "Integer.parseInt";
			}
			if("Long".equalsIgnoreCase(type)){
				return "Long.parseLong";
			}
			if("Double".equalsIgnoreCase(type)){
				return "Double.parseDouble";
			}
			if("Float".equalsIgnoreCase(type)){
				return "Float.parseFloat";
			}
			return "";
		}
		
	}

}
